package com.thb.index.util;


import java.io.IOException;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LucenceUtils {
	
	private static Logger logger = LoggerFactory.getLogger(LucenceUtils.class); 
	
	private static IndexWriter indexWriter = null;
	
	private static DirectoryReader indexReader = null;
	
	public synchronized static IndexWriter getWriter(Directory directory,IndexWriterConfig config){
		
		logger.info("=================================getWriter");
		
		if(indexWriter == null){
			try {
				logger.info("=================================create Writer");
				indexWriter = new IndexWriter(directory, config);
				return indexWriter;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}else{
			return indexWriter;
		}
		
	}
	
	public synchronized static IndexSearcher getSearcher(Directory directory) {
		
		logger.info("=================================getSearcher");
		
		try {
			if(indexReader==null) {
				logger.info("=================================create Searcher");
				indexReader = DirectoryReader.open(directory);
			} else {
				
				DirectoryReader tr = DirectoryReader.openIfChanged(indexReader);
				if(tr!=null) {
					logger.info("=================================changed Searcher");
					indexReader.close();
					indexReader = tr;
				}
			}
			return new IndexSearcher(indexReader);
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	

}


